#version 120

varying vec3 NEye;
varying vec4 PEye;

// Function that computes the color of a fragment, using the standard OpenGL lighting model:

vec4 lighting (vec3 n, vec4 p)
{
  n = normalize(n);
  vec3 s = vec3(0.0);
  vec4 diffuseComponent = vec4(0.0);
  vec4 ambientComponent = vec4(0.0);
  vec4 specularComponent = vec4(0.0);
  ambientComponent = ambientComponent + diffuseComponent;
  for(int i = 0; i < gl_LightSource.length(); i = i + 1){
  s = normalize(gl_LightSource[i].position - p).xyz; // vector from p to light #0

  // Compute the diffuse reflectance (u_s dot u_n):
  float diffuseReflectance = clamp(dot(s, n), 0.0, 1.0);  // dot product involved in diffuse reflection

  // Multiply this by the product of light color (light #0) and material color:
  diffuseComponent += gl_FrontLightProduct[i].diffuse*diffuseReflectance;

  // Computer r and v vectors needed for specular lighting:
  vec3 r = normalize(-s - 2.0*dot(-s, n)*n); // light vector reflected around the normal
  vec3 v = normalize(-p.xyz);                // vector toward eye (0,0,0) from point p

  // Compute the specular reflectance (u_r dot u_v)^f:
  float specularReflectance = pow(max(0.0, dot(r, v)), gl_FrontMaterial.shininess);
 
  // Multiply this by the product of light color (light #0) and material color:
  specularComponent += gl_FrontLightProduct[i].specular*specularReflectance;

  // Compute ambient component:
  ambientComponent += gl_FrontLightProduct[i].ambient;
  }
  // Compute the global ambient light (as described in Lab #4). Note that this is 
  // for the whole scene, and is not tied to any particular light:
  vec4 globalAmbientComponent = gl_FrontLightModelProduct.sceneColor;

  // Total color just adds all these up...
  vec4 totalColor = ambientComponent + diffuseComponent + specularComponent + globalAmbientComponent;

  // We tried changing the red component to 1.0, in class:
  //totalColor.r = 1.0;
  return clamp(totalColor, vec4(0.0), vec4(1.0));
}

uniform sampler2D tex;
// Main fragment program: computes a color by calling our 'lighting' function:
void main ()
{
  vec4 ct;
  vec4 texel;
  //float af;
  //af = gl_FrontMaterial.diffuse.a;
  texel = texture2D(tex,gl_TexCoord[0].st);
  ct = texel.rgba;
  //gl_FragColor = lighting(NEye, PEye);
  gl_FragColor = lighting(NEye, PEye) * ct;
}




